import React from 'react';
import _ from 'lodash';
import router from 'umi/router';
import moment from 'moment';
import { Tooltip } from 'antd';
import { utils, BaseTable, TextWithTags, NumberView } from '@/components/BaseTable';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */

const categories = [
  'dynamic_total_price',
  'dynamic_sale_price',
  'dynamic_stock_price',
  'dynamic_plan_price',
  'dynamic_right_price',
  'before_real_supply',
  'before_real_sign',
  'before_removal',
  'daterange_real_supply_yyyy_mm',
  'daterange_real_sign_yyyy_mm',
  'daterange_removal_yyyy_mm',
  'daterange_real_supply_sum',
  'daterange_real_supply_exp_sum',
  'daterange_real_sign_sum',
  'daterange_real_sign_exp_sum',
  'daterange_removal_sum',
  'daterange_removal_exp_sum',
  'overall_real_supply',
  'overall_real_sign',
  'overall_removal',
];
const formatNumber = num => (num === null || num === 'null' ? null : _.round(_.toNumber(num), 4));
export const buildRowStructure = list => {
  const unionArr = _.filter(list, x => x.groupCode === 'dynamic_total_price');
  const rows = [];
  unionArr.forEach(value => {
    const initSum = {};
    categories.forEach(category => {
      initSum[category] = {};
    });
    rows.push({
      ...initSum,
      id: value.orgId,
      pid: value.parentOrgId,
      name: value.orgName,
      orgType: value.orgType,
      isParking: value.isParking,
    });
  });

  list.forEach(value => {
    const items = _.filter(rows, x => x.id === value.orgId);
    if (items && items.length > 0) {
      const row = items[0];
      // isParking 是否是车位
      row[value.groupCode] = {
        roomRemovalRate: formatNumber(value.roomRemovalRate), // 房间去化率
        carPlateRemovalRate: formatNumber(value.carPlateRemovalRate), // 车位去化率
        areaRemovalRate: formatNumber(value.areaRemovalRate), // 面积去化率（房间）
        totalPriceRemovalRate: formatNumber(value.totalPriceRemovalRate), // 总金额去化率（房间+车位）
        totalCountRemovalRate: formatNumber(value.totalCountRemovalRate), // 总套数去化率（房间+车位）
        roomTotalPriceRemovalRate: formatNumber(value.roomTotalPriceRemovalRate), // 房间金额去化率
        carPlateTotalPriceRemovalRate: formatNumber(value.carPlateTotalPriceRemovalRate), // 车位金额去化率
        roomAvgPrice: formatNumber(value.roomAvgPrice), // 房间均价
        carPlateAvgPrice: formatNumber(value.carPlateAvgPrice), // 车位均价
        roomTotalPrice: formatNumber(value.roomTotalPrice), // 房间总金额
        carPlateTotalPrice: formatNumber(value.carPlateTotalPrice), // 车位总金额
        totalPrice: formatNumber(value.totalPrice), // 总金额
        roomCount: formatNumber(value.roomCount), // 房间套数
        carPlateCount: formatNumber(value.carPlateCount), // 车位个数
        rightPrice: formatNumber(value.rightPrice), // 权益货值
        area: formatNumber(value.area), // 面积
      };
    }
  });
  return rows;
};

export const hasChildren = (list, item) => {
  const items = _.filter(list, element => element.pid === item.id);
  return items.length > 0;
};
export const buildTree = (list, pid = '') => {
  const tree = [];
  list.forEach(value => {
    const x = value;
    if (`${x.pid}` === pid) {
      if (hasChildren(list, x)) {
        delete x.isLeaf;
        x.children = [];
        x.children = buildTree(list, x.id);
      } else {
        delete x.children;
        x.isLeaf = true;
      }
      tree.push(x);
    }
  });
  return tree;
};
export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

export const levelTree = (list, level) => {
  const cloneList = _.cloneDeep(list);
  let filterItem = [];
  if (level === 'region') {
    filterItem = _.filter(
      cloneList,
      v => v.orgType === 'org_wanda_group' || v.orgType === 'org_business_division',
    );
  }
  if (level === 'cityCompany') {
    filterItem = _.filter(
      cloneList,
      v =>
        v.orgType === 'org_wanda_group' ||
        v.orgType === 'org_business_division' ||
        v.orgType === 'org_city_company',
    );
  }
  if (level === 'project') {
    filterItem = _.filter(
      cloneList,
      v =>
        v.orgType === 'org_wanda_group' ||
        v.orgType === 'org_business_division' ||
        v.orgType === 'org_city_company' ||
        v.orgType === 'org_project',
    );
  }
  if (level === 'stage') {
    filterItem = _.filter(
      cloneList,
      v =>
        v.orgType === 'org_wanda_group' ||
        v.orgType === 'org_business_division' ||
        v.orgType === 'org_city_company' ||
        v.orgType === 'org_project' ||
        v.orgType === 'org_stage',
    );
  }
  return filterItem;
};

export const getArrayNumbers = (text, division = 1) => {
  if (!_.isEmpty(text) && text.indexOf('/') > -1) {
    // text.split('/')
    const temp = [];
    _.forEach(text.split('/'), value => {
      temp.push((_.trim(value) * 1) / division);
    });
    text = temp;
  } else {
    text = (text * 1) / division;
  }

  return text;
};

// 套数/车位数
export const buildBaseColumnNum = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'num')) {
    fixedColumns.push({
      key: `${category.key}num`,
      dataKey: `${category.key}num`,
      title: '',
      align: 'right',
      width: attributesCheckeds.length === 1 ? 160 : 130,
      dataGetter: ({ rowData }) => {
        const number = [];
        if (!rowData[category.key] || _.isEmpty(rowData[category.key])) {
          return '';
        }
        const rowDataX = rowData[category.key];
        if (_.isNumber(rowDataX.roomCount)) {
          number.push(rowDataX.roomCount);
        }
        if (_.isNumber(rowDataX.carPlateCount)) {
          number.push(rowDataX.carPlateCount);
        }
        return utils.calculate.NumberView({
          cellData: number,
          precision: 0,
        });
      },
      headerRenderer: () => (
        <HeaderRenderer type={1}>
          <div>套数/车位数</div>
          <div>(套/个)</div>
        </HeaderRenderer>
      ),
    });
  }
};

// 套数车位数去化率
export const buildBaseColumnNumRate = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'num')) {
    fixedColumns.push({
      key: `${category.key}numRate`,
      dataKey: `${category.key}numRate`,
      title: '',
      align: 'right',
      width: attributesCheckeds.length === 1 ? 160 : 130,
      dataGetter: ({ rowData }) => {
        const number = [];
        if (!rowData[category.key] || _.isEmpty(rowData[category.key])) {
          return '';
        }
        const rowDataX = rowData[category.key];
        if (_.isNumber(rowDataX.totalCountRemovalRate)) {
          number.push(rowDataX.totalCountRemovalRate);
        }
        return utils.calculate.NumberView({
          cellData: number,
          precision: 1,
          suffix: '%',
        });
      },
      // cellRenderer: <TextWithTags precision={0} />,
      headerRenderer: () => (
        <div>
          <div>套数/车位数</div>
          <div>(%)</div>
        </div>
      ),
    });
  }
};

// 面积
export const buildBaseColumnArea = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'area')) {
    fixedColumns.push({
      key: `${category.key}area`,
      dataKey: `${category.key}area`,
      title: '',
      align: 'right',
      width: 150,
      dataGetter: ({ rowData }) => {
        const number = [];
        if (rowData[category.key] && _.isNumber(rowData[category.key])) {
          return '';
        }
        const rowDataX = rowData[category.key];
        if (_.isNumber(rowDataX.area)) {
          number.push(rowDataX.area);
        }
        return number;
      },
      cellRenderer: <NumberView precision={2} />,
      headerRenderer: () => (
        <div>
          <div>面积</div>
          <div>(平米)</div>
        </div>
      ),
    });
  }
};

// 面积去化率（房间）
export const buildBaseColumnAreaRate = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'area')) {
    fixedColumns.push({
      key: `${category.key}areaRemovalRate`,
      dataKey: `${category.key}areaRemovalRate`,
      title: '',
      align: 'right',
      width: attributesCheckeds.length === 1 ? 160 : 100,
      dataGetter: ({ rowData }) => {
        if (rowData[category.key] && _.isNumber(rowData[category.key].areaRemovalRate)) {
          return utils.calculate.NumberView({
            cellData: rowData[category.key].areaRemovalRate,
            precision: 1,
            suffix: '%',
          });
        }
        return utils.calculate.NumberView({
          cellData: null,
          precision: 1,
          suffix: '%',
        });
      },
      // cellRenderer: <NumberView precision={2} />,
      headerRenderer: () => (
        <div>
          <div>面积</div>
          <div>(%)</div>
        </div>
      ),
    });
  }
};

// 均价 roomAvgPrice carPlateAvgPrice 车位房间均价
export const buildBaseColumnAveragePrice = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'aver')) {
    fixedColumns.push({
      key: `${category.key}averagePrice`,
      dataKey: `${category.key}averagePrice`,
      title: '',
      align: 'right',
      width: attributesCheckeds.length === 1 ? 160 : 130,
      headerRenderer: () => (
        <HeaderRenderer type={2}>
          <div>均价</div>
          <div>(元/平米,个)</div>
        </HeaderRenderer>
      ),
      dataGetter: ({ rowData }) => {
        if (!rowData[category.key] || _.isEmpty(rowData[category.key])) {
          return '';
        }
        const rowDataX = rowData[category.key];

        const number = [];
        if (_.isNumber(rowDataX.roomAvgPrice)) {
          number.push(rowDataX.roomAvgPrice);
        }
        if (_.isNumber(rowDataX.carPlateAvgPrice)) {
          number.push(rowDataX.carPlateAvgPrice);
        }
        return utils.calculate.NumberView({
          cellData: number,
          precision: 0,
        });
      },
    });
  }
};

// 货值 车位 房间 总金额
export const buildBaseColumnSum = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'price')) {
    fixedColumns.push({
      key: `${category.key}sumValue11`,
      dataKey: `${category.key}sumValue11`,
      title: '',
      align: 'right',
      width: 240,
      dataGetter: ({ rowData }) => {
        if (!rowData[category.key] || _.isEmpty(rowData[category.key])) {
          return '';
        }

        const rowDataX = rowData[category.key];

        const number = [];

        if (_.isNumber(rowDataX.carPlateTotalPrice) && _.isNumber(rowDataX.roomTotalPrice)) {
          number.push(_.sum([rowDataX.totalPrice / 10000]));
        }

        if (_.isNumber(rowDataX.roomTotalPrice)) {
          number.push(rowDataX.roomTotalPrice / 10000);
        }
        if (_.isNumber(rowDataX.carPlateTotalPrice)) {
          number.push(_.sum([rowDataX.carPlateTotalPrice / 10000]));
        }

        return utils.calculate.NumberView({
          cellData: number,
          precision: 0,
        });
      },
      // cellRenderer: <TextWithTags precision={0} />,
      headerRenderer: () => (
        <HeaderRenderer type={3}>
          <div>金额</div>
          <div>(万元：合计/房源/车位)</div>
        </HeaderRenderer>
      ),
    });
  }
};

// 货值 roomTotalPriceRemovalRate 房间金额去化率 totalPriceRemovalRate
export const buildBaseColumnSumRate = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'price')) {
    fixedColumns.push({
      key: `${category.key}sumValueRate`,
      dataKey: `${category.key}sumValueRate`,
      title: '',
      align: 'right',
      width: 100,
      dataGetter: ({ rowData }) => {
        if (!rowData[category.key] || _.isEmpty(rowData[category.key])) {
          return '';
        }
        const rowDataX = rowData[category.key];
        const number = [];
        if (_.isNumber(rowDataX.totalPriceRemovalRate)) {
          number.push(_.sum([rowDataX.totalPriceRemovalRate]));
        }
        return utils.calculate.NumberView({
          cellData: number,
          precision: 1,
          suffix: '%',
        });
      },
      // cellRenderer: <TextWithTags precision={0} />,
      headerRenderer: () => (
        <div>
          <div>金额</div>
          <div>(%)</div>
        </div>
      ),
    });
  }
};

// 权益货值
export const buildBaseColumnQuityValue = ({ category, attributesCheckeds, fixedColumns }) => {
  if (_.includes(attributesCheckeds, 'price')) {
    fixedColumns.push({
      key: `${category.key}sumValue3`,
      dataKey: `${category.key}sumValue3`,
      title: '',
      align: 'right',
      width: 100,
      dataGetter: ({ rowData }) => {
        if (!rowData[category.key] || _.isEmpty(rowData[category.key])) {
          return '';
        }
        const rowDataX = rowData[category.key];
        const number = [];
        number.push(_.sum([rowDataX.rightPrice / 10000]));
        return utils.calculate.NumberView({
          cellData: number,
          precision: 0,
        });
      },
      // cellRenderer: <TextWithTags precision={0} />,
      // headerRenderer: () => (
      //   <div>
      //     <div>金额</div>
      //     <div>(万元)</div>
      //   </div>
      // ),
    });
  }
};

// 返回  套数(个)/面积/均价/货值
export const buildBaseColumns = ({ category, attributesCheckeds, fixedColumns }) => {
  // 套数/车位数
  buildBaseColumnNum({ category, attributesCheckeds, fixedColumns });
  // 面积
  buildBaseColumnArea({ category, attributesCheckeds, fixedColumns });
  // 均价
  buildBaseColumnAveragePrice({ category, attributesCheckeds, fixedColumns });
  // 货值
  buildBaseColumnSum({ category, attributesCheckeds, fixedColumns });
};

export const getFixedColumns = (titleTree, attributesCheckeds) => {
  const cloneTitle = _.cloneDeep(titleTree);
  const fixedColumns = [];
  fixedColumns.push({
    key: 'name',
    dataKey: 'name',
    title: '',
    width: 260,
    frozen: 'left',
    cellRenderer: ({ rowData }) => (
      <Tooltip placement="topLeft" title={rowData.name}>
        <div
          style={{
            width: '100%',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
          }}
        >
          {rowData.name}
        </div>
      </Tooltip>
    ),
  });
  _.each(cloneTitle, item => {
    _.each(item.children, category => {
      if (category.type === 3) {
        buildBaseColumnNumRate({ category, attributesCheckeds, fixedColumns });
        buildBaseColumnAreaRate({ category, attributesCheckeds, fixedColumns });
        buildBaseColumnSumRate({ category, attributesCheckeds, fixedColumns });
      } else if (category.type === 1) {
        // dynamicquityValue  权益货值
        buildBaseColumnQuityValue({
          category,
          attributesCheckeds,
          fixedColumns,
        });
      } else {
        // 固定4列格式 套数、面积、均价、金额
        buildBaseColumns({
          category,
          attributesCheckeds,
          fixedColumns,
        });
      }
    });
  });
  return fixedColumns;
};

export const getTitleTree = deadline => {
  const year = deadline.split('-')[0];
  const month = deadline.split('-')[1];
  const titleTree = [
    {
      name: '组织/项目/分期',
      key: 'id',
      colspan: 1,
      rowspan: 4,
    },
    {
      name: '全盘动态货值',
      key: 'dynamic',
      rowspan: 1,
      children: [
        {
          name: '总货值(不含未推售车位)',
          key: 'dynamic_total_price',
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '已售货值',
          key: 'dynamic_sale_price',
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '存货货值',
          key: 'dynamic_stock_price',
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '规划货值',
          key: 'dynamic_plan_price',
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: (
            <div style={{ textAlign: 'center' }}>
              <div>权益货值</div>
              <div>(万元)</div>
            </div>
          ),
          key: 'dynamic_right_price',
          colspan: 1,
          rowspan: 3,
          type: 1,
          attributes: ['price'],
        },
      ],
    },
    {
      name: `${year - 1}年及以前`,
      key: 'before',
      rowspan: 1,
      children: [
        {
          name: '累计实际供货',
          key: 'before_real_supply',
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '累计实际签约',
          key: 'before_real_sign',
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '去化率',
          key: 'before_removal',
          colspan: 3,
          type: 3,
          attributes: ['num', 'area', 'price'],
        },
      ],
    },
  ];
  for (let i = 1; i <= month * 1; i += 1) {
    titleTree.push({
      name: `${year}年${i < 10 ? 0 : ''}${i}月`,
      key: `daterange_${year}_${i}`,
      rowspan: 1,
      children: [
        {
          name: '本月实际可售',
          key: `daterange_real_supply_${year}_${i < 10 ? 0 : ''}${i}`,
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '本月实际签约',
          key: `daterange_real_sign_${year}_${i < 10 ? 0 : ''}${i}`,
          colspan: 4,
          type: 4,
          attributes: ['num', 'area', 'aver', 'price'],
        },
        {
          name: '去化率',
          key: `daterange_removal_${year}_${i < 10 ? 0 : ''}${i}`,
          colspan: 3,
          type: 3,
          attributes: ['num', 'area', 'price'],
        },
      ],
    });
  }
  titleTree.push(
    ...[
      {
        name: `${year}年合计`,
        key: 'current',
        rowspan: 1,
        children: [
          {
            name: '年度实际可售',
            key: 'daterange_real_supply_sum',
            colspan: 4,
            type: 4,
            attributes: ['num', 'area', 'aver', 'price'],
          },
          {
            name: '年度实际可售(不含未推售阶段自持存货)',
            key: 'daterange_real_supply_exp_sum',
            colspan: 4,
            type: 4,
            attributes: ['num', 'area', 'aver', 'price'],
          },
          {
            name: '年度实际签约',
            key: 'daterange_real_sign_sum',
            colspan: 4,
            type: 4,
            attributes: ['num', 'area', 'aver', 'price'],
          },
          // {
          //   name: '年度实际签约(不含未推售阶段自持存货)',
          //   key: 'daterange_real_sign_exp_sum',
          //   colspan: 4,
          //   type: 4,
          //   attributes: ['num', 'area', 'aver', 'price'],
          // },
          {
            name: '年度去化率',
            key: 'daterange_removal_sum',
            colspan: 3,
            type: 3,
            attributes: ['num', 'area', 'price'],
          },
          {
            name: '年度去化率(不含未推售阶段自持存货)',
            key: 'daterange_removal_exp_sum',
            colspan: 3,
            type: 3,
            attributes: ['num', 'area', 'price'],
          },
        ],
      },
      {
        name: '整盘',
        key: 'overall_removal',
        rowspan: 1,
        children: [
          {
            name: '累计实际供货',
            key: 'overall_real_supply',
            colspan: 4,
            type: 4,
            attributes: ['num', 'area', 'aver', 'price'],
          },
          {
            name: '累计实际签约',
            key: 'overall_real_sign',
            colspan: 4,
            type: 4,
            attributes: ['num', 'area', 'aver', 'price'],
          },
          {
            name: '去化率',
            key: 'overall_removal',
            colspan: 3,
            type: 3,
            attributes: ['num', 'area', 'price'],
          },
        ],
      },
    ],
  );
  return titleTree;
};
